package devyouk.util.excel.util;

import devyouk.util.excel.ColumnConfig;
import devyouk.util.excel.cellAdapter.CellValueAdapter;
import devyouk.util.excel.cellAdapter.DefaultCellValueAdapter;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Utils {

    public static List<ColumnConfig> getColumnConfigsFromType(Class claz) {
        Method[] methods = claz.getMethods();
        return Arrays.stream(methods)
                .filter(Utils::isGetterMethod)
                .map(method -> {
                    String name = method.getName();
                    char[] chars = name.substring(3).toCharArray();
                    chars[0] = Character.toLowerCase(chars[0]);
                    name = new String(chars);
                    Class<?> returnType = method.getReturnType();
                    CellValueAdapter adapter = DefaultCellValueAdapter.getAdapterOfType(returnType);
                    ColumnConfig columnConfig = new ColumnConfig(name, name);
                    columnConfig.setCellValueAdapter(adapter);
                    return columnConfig;
                })
                .collect(Collectors.toList());
    }

    private static boolean isGetterMethod(Method method) {
        return method.getName().startsWith("get") &&
                !method.getReturnType().equals(void.class) &&
                !method.getName().equalsIgnoreCase("getClass") &&
                method.getParameterCount() == 0;
    }

    public static List<Map<String,Object>> getDataSetFromBeans(List<Object> beans) {
        return beans.stream()
                .map(o -> (Map<String,Object>) getBeanMap(o))
                .collect(Collectors.toList());
    }

    private static Map getBeanMap(Object o) {
        try {
            Map describe = BeanUtils.describe(o);
            describe.remove("class");
            return describe;
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new IllegalStateException(e);
        }
    }
}
